package com.qianwei.footpath.utils;

import android.content.Context;
import android.media.AudioAttributes;
import android.speech.tts.TextToSpeech;
import android.speech.tts.UtteranceProgressListener;
import android.util.Log;

import java.util.Locale;

/**
 * 文字转语音工具类（封装TextToSpeech）
 * 功能：初始化TTS、播放语音、停止播放、释放资源、设置语言/语速/音调
 */
public class TextToSpeechUtils {
    private static final String TAG = "TextToSpeechUtils";
    private TextToSpeech textToSpeech;
    private boolean isInitialized = false;
    private Context context;
    private Locale defaultLocale = Locale.getDefault(); // 默认系统语言

    // 初始化回调接口
    public interface OnInitListener {
        void onInitSuccess();

        void onInitFailed(int errorCode);
    }

    // 播放状态回调接口
    public interface OnPlayListener {
        void onStart(String utteranceId);

        void onDone(String utteranceId);

        void onError(String utteranceId, int errorCode);
    }

    /**
     * 构造函数（异步初始化TTS）
     *
     * @param context  上下文
     * @param listener 初始化结果回调
     */
    public TextToSpeechUtils(Context context, OnInitListener listener) {
        this.context = context.getApplicationContext();
        initTextToSpeech(listener);
    }

    private void initTextToSpeech(OnInitListener listener) {
        textToSpeech = new TextToSpeech(context, status -> {
            if (status == TextToSpeech.SUCCESS) {
                isInitialized = true;
                Log.d(TAG, "设置的语言: " + defaultLocale.getDisplayLanguage());
                setLanguage(defaultLocale);
                setSpeechRate(1.0f);
                setPitch(1.0f);
                if (listener != null) listener.onInitSuccess();
                Log.d(TAG, "TTS初始化成功");
            } else {
                isInitialized = false;
                if (listener != null) listener.onInitFailed(status);
                Log.e(TAG, "TTS初始化失败，错误码: " + status);
            }
        });
    }

    /**
     * 设置TTS语言
     *
     * @param locale 语言区域（如Locale.US、Locale.CHINA）
     * @return 是否设置成功
     */
    public boolean setLanguage(Locale locale) {
        if (!isInitialized) {
            Log.w(TAG, "TTS未初始化，无法设置语言");
            return false;
        }

        int result = textToSpeech.setLanguage(locale);
        if (result == TextToSpeech.LANG_MISSING_DATA || result == TextToSpeech.LANG_NOT_SUPPORTED) {
            Log.e(TAG, "语言不支持或数据缺失: " + locale);
            return false;
        }
        this.defaultLocale = locale;
        return true;
    }

    /**
     * 播放语音
     *
     * @param text        要朗读的文本
     * @param utteranceId 当前播放的唯一标识（可用于回调跟踪）
     * @param listener    播放状态回调
     */
    public void speak(String text, String utteranceId, OnPlayListener listener) {
        if (!isInitialized) {
            Log.w(TAG, "TTS未初始化，无法播放");
            return;
        }
        if (text == null || text.isEmpty()) {
            Log.w(TAG, "播放文本为空");
            return;
        }

        // 设置播放进度监听
        textToSpeech.setOnUtteranceProgressListener(new UtteranceProgressListener() {
            @Override
            public void onStart(String utteranceId) {
                if (listener != null) listener.onStart(utteranceId);
            }

            @Override
            public void onDone(String utteranceId) {
                if (listener != null) listener.onDone(utteranceId);
            }

            @Override
            public void onError(String utteranceId) {
                if (listener != null) listener.onError(utteranceId, -1);
            }

            @Override
            public void onError(String utteranceId, int errorCode) {
                if (listener != null) listener.onError(utteranceId, errorCode);
            }
        });

        // 开始播放（QUEUE_FLUSH表示中断当前播放新内容）
        int result = textToSpeech.speak(text, TextToSpeech.QUEUE_ADD, null, utteranceId);
        if (result == TextToSpeech.ERROR) {
            Log.e(TAG, "播放失败");
        }
    }

    /**
     * 设置语速（默认1.0f）
     *
     * @param rate 0.5f-2.0f（0.5=半速，2.0=双倍速）
     */
    public void setSpeechRate(float rate) {
        if (isInitialized) {
            textToSpeech.setSpeechRate(Math.max(0.5f, Math.min(2.0f, rate)));
        }
    }

    /**
     * 设置音调（默认1.0f）
     *
     * @param pitch 0.5f-2.0f（更低或更高音调）
     */
    public void setPitch(float pitch) {
        if (isInitialized) {
            textToSpeech.setPitch(Math.max(0.5f, Math.min(2.0f, pitch)));
        }
    }

    /**
     * 停止当前播放
     */
    public void stop() {
        if (isInitialized && textToSpeech != null) {
            textToSpeech.stop();
        }
    }

    public void printAvailableLanguages() {
        if (!isInitialized) {
            Log.w(TAG, "TTS未初始化");
            return;
        }
        Locale[] locales = Locale.getAvailableLocales();
        for (Locale locale : locales) {
            int result = textToSpeech.isLanguageAvailable(locale);
            if (result == TextToSpeech.LANG_AVAILABLE || result == TextToSpeech.LANG_COUNTRY_AVAILABLE) {
                Log.d(TAG, "支持语言: " + locale.getDisplayLanguage() + " (" + locale + ")");
            }
        }
    }

    public boolean isInitialized() {
        return isInitialized;
    }

    /**
     * 释放TTS资源（在Activity/Fragment销毁时调用）
     */
    public void release() {
        if (textToSpeech != null) {
            textToSpeech.stop();
            textToSpeech.shutdown();
            isInitialized = false;
        }
    }
}
